package ug.co.icom.kyazze.healthticket;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import ug.co.icom.kyazze.healthticket.data.LoginReturnValue;
import ug.co.icom.kyazze.healthticket.data.User;
import ug.co.icom.kyazze.healthticket.mongoHQ.MongoHQLogin;
import ug.co.icom.kyazze.healthticket.services.ApplicationObject;
import ug.co.icom.kyazze.healthticket.services.IntentFileDownloadService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener {

	private User loggedIn;
	static ProgressDialog dialog;
	private String filepath = "healthTicket_files";
	
	Locale locale = Locale.getDefault();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginactivity_layout);
		
		Button loginButton = (Button) findViewById(R.id.button1);
		loginButton.setOnClickListener(this);

		Button registerButton = (Button) findViewById(R.id.button2);
		registerButton.setOnClickListener(this);

		Button passwordButton = (Button) findViewById(R.id.button3);
		passwordButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.button1)
		{
			try
			{				
				final EditText userNameEditText = (EditText) findViewById(R.id.editText1);
				final EditText passwordEditText = (EditText) findViewById(R.id.editText2);

				String userName = userNameEditText.getText().toString();
				String password = passwordEditText.getText().toString();

				if(!userName.equals("") && !password.equals(""))
				{
					if(userAuthenticated(userName, password))
					{
						CheckBox rem = (CheckBox) findViewById(R.id.checkBox1);
						SharedPreferences settings = getSharedPreferences("ULS", 0);
						SharedPreferences.Editor editor = settings.edit();
						
						ApplicationObject mApplication = (ApplicationObject)getApplicationContext();
						mApplication.setphone_number(Long.valueOf(userName));
						
						//check if local key file exists
						File directory;
						
						ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
						directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
						File file3= new File(directory+"/"+mApplication.getphone_number()+".cpabe");
				
						
						if (!file3.exists()){
							
							Intent intent = new Intent(this, IntentFileDownloadService.class);
							startService(intent);

						}
						

						if(rem.isChecked())
						{

							editor.putBoolean("rem", true);
							editor.putString("uName", loggedIn.PhoneNumber);
							editor.putString("pWord", loggedIn.PassCode);
							editor.putString("fName", loggedIn.FirstName);
							editor.putString("lName", loggedIn.LastName);
							editor.putString("oName", loggedIn.OtherNames);
							editor.putString("add", loggedIn.Address);
							editor.putString("bt", loggedIn.BloodType);
							editor.putBoolean("fem", loggedIn.Female);
							editor.putString("dob", getStringFromDate(loggedIn.DateOfBirth));
							editor.putString("ema", loggedIn.Email);
							
							editor.commit();
						}
						else
						{
							editor.putBoolean("rem", false);
							editor.putString("uName", loggedIn.PhoneNumber);
							editor.putString("pWord", "");
							editor.putString("fName", "");
							editor.putString("lName", "");
							editor.putString("oName", "");
							editor.putString("add", "");
							editor.putString("bt", "");
							editor.putBoolean("fem", false);
							editor.putString("dob", "");
							editor.putString("ema", "");
							
							editor.commit();
						}
						userNameEditText.setText("");
						passwordEditText.setText("");
						Intent i = new Intent(LoginActivity.this, MainActivity.class);
						i.putExtra("user", loggedIn);
						startActivity(i);
					}
					else
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
						builder.setMessage("Wrong User Name or Password");
						builder.setCancelable(true);
						builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();

								userNameEditText.requestFocus();
							}
						});
						AlertDialog alert = builder.create();
						alert.show();
					}
				}
				else if(userName.equals("") && !password.equals(""))
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
					builder.setMessage("Please provide a User Name");
					builder.setCancelable(true);
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();

							userNameEditText.requestFocus();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
				}
				else if(!userName.equals("") && password.equals(""))
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
					builder.setMessage("Please provide a Password");
					builder.setCancelable(true);
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();

							passwordEditText.requestFocus();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
				}
				else
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
					builder.setMessage("Please provide a User Name and Password");
					builder.setCancelable(true);
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();

							userNameEditText.requestFocus();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
			catch(Exception e)
			{

				String message = e.getMessage();
				@SuppressWarnings("unused")
				String err = message;
			}
		}
		else if(v.getId() == R.id.button2)
		{
			Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(i);
		}
		else if(v.getId() == R.id.button3)
		{
			Intent i = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
			startActivity(i);
		}
	}

	private Boolean userAuthenticated(String userName, String password)
	{
		if(userName.equals("admin") && password.equals("admin"))
		{
			return true;
		}
		else
		{
			try
			{
				LoginReturnValue lrv = new LoginReturnValue();
				loggedIn = new User();
				initializeDialog();
				MongoHQLogin userdata = new MongoHQLogin();
				lrv = userdata.execute(userName, password,this.getApplicationContext()).get();
				loggedIn = lrv.user;
				
				ApplicationObject mValue = (ApplicationObject)getApplicationContext();
				boolean x = mValue.isReturnValue();
				//lrv.returnValue

				if(x)
				{
					if(!loggedIn.PhoneNumber.equals(""))
					{
						return true;
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			catch(Exception e)
			{
				return false;
			}			
		}
	}
	
	private String getStringFromDate(Date dateReceived) {
		SimpleDateFormat  dateFormat = new SimpleDateFormat("dd-MM-yyyy", locale);  
		try {  
		    String date = dateFormat.format(dateReceived);  
		    return date;  
		} catch (Exception e) {  
		    return "";
		}
	}
	
	public void initializeDialog() {    
        dialog = ProgressDialog.show(this, "Login Process", "Loading data. Wait...", true);
        dialog.show();
    }
	
	public static void dismissDialog(){        
        dialog.dismiss();
    }


}
